package com.yjkf.zh.admin.service.impl;

import com.yjkf.zh.admin.dao.SysMenuMapper;
import com.yjkf.zh.admin.dao.SysRoleMenuMapper;
import com.yjkf.zh.admin.dao.SysUserMapper;
import com.yjkf.zh.admin.dao.SysUserRoleMapper;
import com.yjkf.zh.admin.model.SysMenu;
import com.yjkf.zh.admin.model.SysRoleMenu;
import com.yjkf.zh.admin.model.SysUser;
import com.yjkf.zh.admin.model.SysUserRole;
import com.yjkf.zh.admin.service.SysMenuService;
import com.yjkf.zh.admin.util.SysConstant;
import com.yjkf.zh.core.page.MybatisPageHelper;
import com.yjkf.zh.core.page.PageRequest;
import com.yjkf.zh.core.page.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

   // @Cacheable()
    @Override
    public List<SysMenu> findByUser(String userName) {
        if(userName == null || "".equals(userName)|| SysConstant.ADMIN.equalsIgnoreCase(userName)){
            return sysMenuMapper.findAll();
        }
      //根据用户名获取个人用户信息
        SysUser sysUser = sysUserMapper.findByName(userName);
        Long userId = sysUser.getId();
        //根据用户名获取全部的菜单列表
        List<SysMenu> sysMenus = sysMenuMapper.findByUserName(userName);
        List<SysMenu> sysMenus1=new ArrayList<>();
        //根据用户名获取roleId
        SysUserRole sysUserRole = sysUserRoleMapper.findByUserId(userId);

        List<SysUserRole> sysUserRoleList = new ArrayList<>();  ////定义不包括自己Id的用户列表
        //根据roleId获取对应的userId列表
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.findByRoleId(sysUserRole.getRoleId());
        //获取不包括自己Id的用户列表
            for(SysUserRole sysUserRole3:sysUserRoles){
                if(!sysUserRole3.getUserId().equals(userId)){
                    sysUserRoleList.add(sysUserRole3);
                }
            }
        //获取与自己同角色的用户Id与菜单的创建者id相同的菜单名称(获取和自己不是同roleId的人创建的menuName)
        for(SysMenu sysMenu:sysMenus) {
            if(!sysUserRoleList.isEmpty()) {
                for (SysUserRole sysUserRole2 : sysUserRoleList) {
                    if (!sysMenu.getCreateId().equals(sysUserRole2.getUserId())) {
                        sysMenus1.add(sysMenu);
                    }
                }
            }else{
                sysMenus1.add(sysMenu);
            }
        }
        //如果获取到的菜单的
        return  sysMenus1;
    }

  // @Cacheable()
    @Override
    public List<SysMenu> findTree(String userName, int menuType) {
        List<SysMenu> sysMenus = new ArrayList<>();
        List<SysMenu> menus = findByUser(userName);
        for(SysMenu menu: menus){
            if(menu.getParentId() == null || menu.getParentId() == 0){
                menu.setLevel(0);
                if(!exists(sysMenus,menu)){
                    sysMenus.add(menu);
                }
            }
        }
        sysMenus.sort((o1, o2) -> o1.getOrderNum().compareTo(o2.getOrderNum()));
        findChildren(sysMenus,menus,menuType);
        return sysMenus;
    }

    @Override
    public int saveForRole(SysMenu record,Long userId) {
        if(record.getId()==null || record.getId()==0){
            sysMenuMapper.insertMenu(record);
            List<SysMenu> sysMenu=sysMenuMapper.selectMenuByCreateId(userId);       //根据用户id获取用户创建的菜单
            //根据用户id，找到对应的角色Id列表
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.findUserRoles(userId);
            for(SysMenu sysMenu1:sysMenu){                     //遍历菜单Id

                //遍历角色Id
                for(SysUserRole sysUserRole:sysUserRoles){
                    //通过角色Id与菜单id查询角色菜单列表
                    if(sysRoleMenuMapper.selectForUser(sysUserRole.getRoleId(),sysMenu1.getId())==null){
                        SysRoleMenu sysRoleMenu = new SysRoleMenu();
                        sysRoleMenu.setMenuId(sysMenu1.getId());
                        sysRoleMenu.setRoleId(sysUserRole.getRoleId());
                        sysRoleMenuMapper.insertSelective(sysRoleMenu);
                    }

                }


                //判断，如果不存在则添加
            }
          return 1;
        }
        if(record.getParentId() == null){
            record.setParentId(0L);
        }
        return sysMenuMapper.updateMenu(record);
    }

    private boolean exists(List<SysMenu> sysMenus,SysMenu sysMenu){
        boolean exist = false;
       // System.out.println(sysMenus.isEmpty());
        for(SysMenu menu:sysMenus){
            if(menu.getId().equals(sysMenu.getId())){
                exist = true;
            }
        }
        return exist;
    }

    @Override
    public int save(SysMenu record) {
        if(record.getId()==null || record.getId()==0){
            return sysMenuMapper.insertMenu(record);
        }
        if(record.getParentId() == null){
            record.setParentId(0L);
        }
        return sysMenuMapper.updateMenu(record);
    }

    @Override
    public int delete(SysMenu record) {
            sysRoleMenuMapper.deleteByMenuId(record.getId());
        return sysMenuMapper.deleteMenu(record.getId());
    }

    @Override
    public int delete(List<SysMenu> records) {
        for(SysMenu record:records){
            delete(record);
        }
        return 1;
    }

    @Override
    public SysMenu findById(Long id) {
        return null;
    }

    //@Cacheable(value = "menu")
    @Override
    public PageResult findPage(PageRequest pageRequest) {
        PageResult pageResult = null;
        Object menuName = pageRequest.getParam("menuName");
        if(menuName!=null){
            pageResult = MybatisPageHelper.findPage(pageRequest,sysMenuMapper,"findPageByName",menuName);
        }else{
            pageResult = MybatisPageHelper.findPage(pageRequest,sysMenuMapper);
        }
        return pageResult;
    }

    private void findChildren(List<SysMenu> SysMenus,List<SysMenu> menus,int menuType){
        for(SysMenu SysMenu:SysMenus){
            List<SysMenu> children = new ArrayList<>();
            for(SysMenu menu : menus){
                if(menuType == 1 && menu.getType() == 2){
                    //如果获取类型不需要按钮，且菜单是按钮型的直接跳过
                    continue ;
                }

                if(SysMenu.getId() != null && SysMenu.getId().equals(menu.getParentId())){
                    menu.setParentName(SysMenu.getMenuName());
                    menu.setLevel(SysMenu.getLevel() + 1);
                    if(!exists(children,menu)){
                        children.add(menu);
                    }
                }
            }
            SysMenu.setChildren(children);
            children.sort((o1, o2) ->o1.getOrderNum().compareTo(o2.getOrderNum()) );
            findChildren(children,menus,menuType);
        }
    }
}
